import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import numeral from 'numeral';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import * as menuService from '../../../services/menus'
import * as IndiDiviService from '../../../services/AccountDivi';
import * as com from '../../../utils/common';
import GrckrdspqkForm from './GrckrdspqkForm'
const daoName = "IndiAccoDivi";
const ButtonGroup = Button.Group;
const renderNumber = (num) => {
    let value = ''
    if (num) {
        value = numeral(num).format('0,0')
    }
    return value
};
const columns = [
    { title: '管辖部门', width: 140, sorter: true, dataIndex: 'Gxbm', key: 'Gxbm', dispaly: true, filter: true },
    { title: '开户网点', width: 140, sorter: true, dataIndex: 'Khwd', key: 'Khwd', dispaly: true, filter: true },
    { title: '开户日', width: 100, sorter: true, key: 'Khr', caption: "Khr", render: data => datetime.format(data.Khr, "yyyy-MM-dd"), dispaly: true, filter: true },
    // { title: '帐号', dataIndex: 'Zhanghao', key: 'Zhanghao', width: 150, sorter: true, dispaly: true, filter: true },
    { title: '卡号', width: 150, sorter: true, dataIndex: 'Khao', key: 'Khao', dispaly: true, filter: true },
    { title: '客户名称', dataIndex: 'Khmc', key: 'Khmc', width: 140, sorter: true, dispaly: true, filter: true },
    { title: '证件号码', dataIndex: 'Sfzh', key: 'Sfzh', width: 180, sorter: true, dispaly: true, filter: true },
    // { title: '起息日', width: 100, sorter: true, key: 'Qxr', caption: "Qxr", render: data => datetime.format(data.Qxr, "yyyy-MM-dd"), dispaly: true, filter: true },
    // { title: '到期日', width: 100, sorter: true, key: 'Dqr', caption: "Dqr", render: data => datetime.format(data.Dqr, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '联系方式', dataIndex: 'Lxfs', key: 'Lxfs', width: 140, sorter: true, dispaly: true, filter: true },
    // { title: '执行利率', dataIndex: 'Ccly', key: 'Ccly', width: 120, sorter: true, dispaly: true, filter: true },
    // { title: '当前余额', className: 'column-money', render: data => com.formatNumber(data.Dqye), caption: "Dqye", key: 'Dqye', width: 130, sorter: true, dispaly: true, filter: true },
];
const controls = [
    { name: 'Sfzh', required: true, type: 'text', label: '证件号码', grid: 12 / 24 },
    // { name: 'Zhanghao', required: true, type: 'text', label: '帐号', grid: 12 / 24 },
    { name: "Khao", label: "卡号", type: "text", grid: 12 / 24 },
    { name: "Gxbm", label: "管辖部门", type: "text", grid: 12 / 24 },
    { name: "Khwd", label: "开户网点", type: "text", grid: 12 / 24 },
    { name: 'Lxfs', required: true, type: 'text', label: '联系方式', grid: 12 / 24 },
    { name: 'Khmc', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
    // { name: 'Ccly', required: true, type: 'text', label: '执行利率', grid: 12 / 24 },
    // { name: 'Dqye', required: true, type: 'alphanum', label: '当前余额', grid: 12 / 24 },
    { name: "Khr", label: "开户日", type: "date", grid: 12 / 24, dataType: "date" },
    // { name: "Qxr", label: "起息日", type: "date", grid: 12 / 24, dataType: "date" },
    // { name: "Dqr", label: "到期日", type: "date", grid: 12 / 24, dataType: "date" },
];
const columnsDivi = [
    { title: '员工ID', dataIndex: 'EMID', key: 'EMID', width: 80, dispaly: false },
    { title: '员工编号', dataIndex: 'EMNO', key: 'EMNO', width: 80, dispaly: true },
    { title: '员工名称', width: 80, sorter: true, dataIndex: 'SysUserName', key: 'SysUserName', dispaly: true },
    { title: '所属机构', width: 100, sorter: true, dataIndex: 'OrganName', key: 'OrganName', dispaly: true },
    { title: '分户日期', width: 80, sorter: true, key: 'DSDT', caption: "DSDT", render: data => datetime.format(data.DSDT, "yyyy-MM-dd"), dispaly: true },
    { title: '分成比例', width: 80, sorter: true, dataIndex: 'DSVL', key: 'DSVL', dispaly: true },
    { title: '当前状态', width: 180, sorter: true, dataIndex: 'DQZT', key: 'DQZT', dispaly: true },
];

const DataTable = dataTableCreate(daoName);
const EditFrom = dataEditCreate(daoName);
class XzgrckrdForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            diviDataSource: [],
            searchData: {},
            diviList: [],
            isDisplay_m: 'block',
            isDisplay_o: 'none',
            lable: '查看申请信息',
            isRDqk: true,
            height: this.props.offsetHeight * 0.55//格局发布
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let sort = {
            field: 'Khr',
            order: 'descend'
        }
        let { orgID, pOrgID, popedomTypes, permID } = this.props
        const pTypes = popedomTypes[permID]
        let whereItems = [];
        let WhereCauses = [];
        //权限控制
        if (pTypes.indexOf('4') === -1) {
            if (pTypes.indexOf('3') !== -1 && pTypes.indexOf('J') === -1) {
                whereItems.push({
                    FieldName: "OrganID",
                    Operator: "=",
                    FieldValues: '' + orgID
                });
            } else if (pTypes.indexOf('J') !== -1) {
                whereItems.push({
                    FieldName: "ParentOrganID",
                    Operator: "=",
                    FieldValues: '' + pOrgID
                });
            }
            WhereCauses.push({
                WhereItems: whereItems,
                RelationSign: "AND"
            })
        }
        let seeks = WhereCauses;
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort, seeks: seeks }
        });
        this.loadOptionData();
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    onSelectChangeHandler(newList) {
        this.state.diviList = [];
        let diviList = this.state.diviList
        newList.map(data => {
            diviList.push(data)
        })
        this.setState({ diviList })
    }
    searchHandle(data) {
        this.state.searchData = data
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    diviAdd() {
        let data = {}
        let formatDate = null
        const form = this.refs.diviForm.getForm();
        let isOK = true;
        form.validateFields((err, values) => {
            if (!err) {
                if (values.ZB === undefined || values.ZB === '') {
                    message.error('占比不能为空！');
                    isOK = false;
                }
                if (values.YG === undefined || values.YG === '') {
                    message.error('员工不能为空！');
                    isOK = false;
                }
                if (values.YF === undefined) {
                    message.error('月份不能为空！');
                    isOK = false;
                }
                if (values.ZB === undefined) {
                    values.ZB = '';
                }
                if (values.YF === undefined) {
                    values.YF = '';
                }
                if (values.YF !== '') {
                    formatDate = new Date(values.YF.get('year'), values.YF.get('month'), 1, 8, 0, 0)
                }
                data.DSVL = Number(values.ZB);
                data.DSDT = values.YF === !values.YF ? null : formatDate
            }
        });
        if (!isOK) {
            return;
        }
        if (this.state.searchData.ID < 0 || this.state.searchData.No.indexOf(":") > 0) {
            message.error('分配失败！员工：' + this.state.searchData.Name + '为虚拟员工，不支持业绩分配！请重新选择')
            return;
        }
        data.EMID = this.state.searchData.ID;                    //员工ID
        data.EMNO = this.state.searchData.No;                    //员工编号
        data.SysUserName = this.state.searchData.Name;           //员工名称
        data.OrganName = this.state.searchData.Organization.Name;//所属机构   
        data.DQZT = "待审批";
        let diviDs = this.state.diviDataSource
        //验证：添加的员工是否重复，并累加已分配比例是否超出100%
        for (let i = 0; i < diviDs.length; i++) {
            if (Number(diviDs[i]["EMID"]) === Number(data["EMID"])) {
                message.error('分配失败！所选员工已分配，请重新选择员工分配！');
                return;
            }
        }
        let diviSum = data.DSVL;
        diviDs.map(d => diviSum += d.DSVL)
        if (diviSum > 100) {
            message.error('占比不能大于100！');
            return;
        }
        let date = this.props.odsDate.substring(0, 10).replace("-", "").replace("-", "")
        let odsDate1 = Number(date.substring(7, 8))
        let odsDate2 = date.substring(6, 8)
        let odsDate3 = Number(date.substring(4, 6))
        let nowdate = datetime.format(data.DSDT,"yyyy-MM-dd").substring(0, 10).replace("-", "").replace("-", "")
        let nowdate1 = Number(nowdate.substring(4, 6))
        console.log(odsDate1,odsDate2,odsDate3,nowdate1)
        if (odsDate1 > 1 && odsDate2 != '11' && odsDate2 != '21' && odsDate2 != '31' && odsDate3 > nowdate1) {
            message.error('数据日期已大于本月1号,不能选择上月及以前日期！');
            return;
        }
        diviDs.push(data);
        this.setState({ diviDataSource: diviDs });
    }
    diviDel() {
        let keys = this.refs.table3.getSelectedRowKeys();
        keys.sort();
        const datas = this.refs.table3.state.datas;
        let indexs = [];
        const keyName = 'EMID'
        datas.map((d, k) => {
            for (let i = 0; i < keys.length; i++) {
                if (d[keyName] === keys[i]) {
                    indexs.push(k)
                }
            }
        })
        let diviDsource = this.state.diviDataSource;
        for (let j = indexs.length - 1; j >= 0; j--) {
            const k = indexs[j]
            diviDsource.splice(k, 1)
        }
        this.setState({ diviDataSource: diviDsource })
    };
    diviSubmit() {
        const datas = this.refs.table3.state.datas;
        let len = this.props.selectedRowKeys.length;
        let key = this.props.selectedRowKeys;
        let mainData = this.state.diviList;
        if (len <= 0) {
            message.error('请选择要认定的数据行!');
            return;
        }
        if (datas.length <= 0) {
            message.error('请添加认定信息!');
            return;
        }
        let dsvlSum = 0;
        let dataSource = []
        datas.map(d => {
            dsvlSum = dsvlSum + d.DSVL;
            let data = {
                EMID: Number(d.EMID),
                DSDT: d.DSDT,
                DSVL: Number(d.DSVL),
                DQZT: d.DQZT
            }
            dataSource.push(data);
        })
        if (dsvlSum !== 100) {
            message.error('分配比例必须为100%');
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要提交给审批人 ${datas.map(d => '【' + d.SysUserName + '】')} 的认定申请吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                IndiDiviService.IndiAccoDiviSq({ mainData, dataSource }
                ).then(function (data) {
                    if (data === 'OK') {
                        this.state.diviDataSource = []
                        this.state.diviList = []
                        const form = this.refs.diviForm.getForm();
                        form.resetFields();
                        this.props.dispatch({
                            type: `${daoName}/setSelectedRowKeys`,
                            payload: { selectedRowKeys: [] }
                        });
                        message.success('认定申请提交成功！')
                    } else {
                        message.error('认定申请提交失败！' + data)
                        return;
                    }
                    this.componentDidMount();
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
                let daoName = 'IndiAccoDiviSq'
                let sort = {
                    field: 'TJRQ',
                    order: 'descend'
                }
                this.props.dispatch({
                    type: `${daoName}/fetch`,
                    payload: { daoName, page: 1, pageSize: 20, sorter: sort }
                });
            }
        });
    };
    findSpqk() {
        if (this.state.isRDqk) {
            this.state.lable = "返回申请"
            this.state.isDisplay_m = "none"
            this.state.isDisplay_o = "block"
            this.state.isRDqk = false
            this.state.height = this.props.offsetHeight * 0.4
        } else {
            this.state.lable = "查看申请情况"
            this.state.isDisplay_m = "block"
            this.state.isDisplay_o = "none"
            this.state.isRDqk = true
            this.state.height = this.props.offsetHeight * 0.55
        }
        this.setState({})
    }
    findData() {
        let { orgID, pOrgID, popedomTypes, permID } = this.props
        const pTypes = popedomTypes[permID]
        let kh = ""
        let khmc = ""
        let zjhm = ""
        const form = this.refs.findForm.getForm();
        form.validateFields((err, values) => {
            if (!err) {
                if (values.KH === undefined) {
                    values.KH = ""
                }
                if (values.KHMC === undefined) {
                    values.KHMC = ""
                }
                if (values.ZJHM === undefined) {
                    values.ZJHM = ""
                }
                kh = values.KH;
                khmc = values.KHMC;
                zjhm = values.ZJHM;
            }
        });
        let seeks = [];
        let whereItems = [];
        let WhereCauses = [];
        if (pTypes.indexOf('4') === -1) {
            if (pTypes.indexOf('3') !== -1 && pTypes.indexOf('J') === -1) {
                whereItems.push({
                    FieldName: "OrganID",
                    Operator: "=",
                    FieldValues: '' + orgID
                });
            } else if (pTypes.indexOf('J') !== -1) {
                whereItems.push({
                    FieldName: "ParentOrganID",
                    Operator: "=",
                    FieldValues: '' + pOrgID
                });
            }
        }
        if (zjhm !== '' && khmc === '' && kh === '') {
            whereItems.push({
                FieldName: "Sfzh",
                Operator: "like",
                FieldValues: zjhm
            });
        } else if (kh === '' && zjhm === '' && khmc !== '') {
            whereItems.push({
                FieldName: "Khmc",
                Operator: "like",
                FieldValues: khmc
            });
        } else if (kh !== '' && zjhm === '' && khmc === '') {
            whereItems.push({
                FieldName: "Khao",
                Operator: "like",
                FieldValues: kh
            });
        } else if (kh !== '' && zjhm !== '' && khmc === '') {
            whereItems.push({
                FieldName: "Khao",
                Operator: "like",
                FieldValues: kh
            });
            whereItems.push({
                FieldName: "Sfzh",
                Operator: "like",
                FieldValues: zjhm
            });
        } else if (kh !== '' && khmc !== '' && zjhm === '') {
            whereItems.push({
                FieldName: "Khao",
                Operator: "like",
                FieldValues: kh
            });
            whereItems.push({
                FieldName: "Khmc",
                Operator: "like",
                FieldValues: khmc
            });
        } else if (kh === '' && khmc !== '' && zjhm !== '') {
            whereItems.push({
                FieldName: "Sfzh",
                Operator: "like",
                FieldValues: zjhm
            });
            whereItems.push({
                FieldName: "Khmc",
                Operator: "like",
                FieldValues: khmc
            });
        } else if (kh !== '' && khmc !== '' && zjhm !== '') {
            whereItems.push({
                FieldName: "Sfzh",
                Operator: "like",
                FieldValues: zjhm
            });
            whereItems.push({
                FieldName: "Khmc",
                Operator: "like",
                FieldValues: khmc
            });
            whereItems.push({
                FieldName: "Khao",
                Operator: "like",
                FieldValues: kh
            });
        }
        WhereCauses.push({
            WhereItems: whereItems,
            RelationSign: "AND"
        })
        seeks = WhereCauses;
        if (whereItems.length <= 0) {
            this.props.dispatch({
                type: `${daoName}/fetch`,
                payload: { daoName }
            });
        } else {
            this.props.dispatch({
                type: `${daoName}/fetch`,
                payload: { daoName, seeks }
            });
        }
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    dateChange() {
        let date = this.props.odsDate.substring(0, 10).replace("-", "").replace("-", "")
        let odsDate1 = Number(date.substring(7, 8))
        let odsDate2 = date.substring(6, 8)
        let nowdate = ""
    }
    render() {
        let { showEdit, record, permID, popedomTypes, cmDate, orgID, pOrgID, offsetHeight, odsDate } = this.props
        const dsCount = this.state.diviDataSource.length //列表数量
        const isDisabled = dsCount > 0 ? true : false; //是否锁定月份
        let data = [{ value: '1', label: '查询', onClick: this.findData.bind(this) }, { value: '2', label: this.state.lable, onClick: this.findSpqk.bind(this) }]
        const controlsDivi = [
            { name: 'YG', required: false, type: 'search', label: '员工', grid: 5 / 24, layout: { labelSpan: 8, wrapperSpan: 13 }, fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this), permID: permID } },
            { name: 'ZB', required: false, type: 'input-number-min1', label: '分配比例(%)', grid: 5 / 24, layout: { labelSpan: 12, wrapperSpan: 9 } },
            { name: 'YF', required: false, type: 'month', label: '月份', grid: 5 / 24, layout: { labelSpan: 6, wrapperSpan: 13 }, isDisabled: isDisabled },
            { name: 'BT', required: false, type: 'button-group', data: [{ value: '1', label: '添加', onClick: this.diviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }, { value: '3', label: '提交', onClick: this.diviSubmit.bind(this) }], grid: 9 / 24 },
        ];
        const controlsFilter = [
            { name: 'KH', required: false, type: 'text', label: '卡号', grid: 6 / 24, layout: { labelSpan: 7, wrapperSpan: 16 }, placeholder: '请输入卡号...' },
            { name: 'KHMC', required: false, type: 'text', label: '客户名称', grid: 6 / 24, placeholder: '请输入客户姓名...', layout: { labelSpan: 7, wrapperSpan: 16 } },
            { name: 'ZJHM', required: false, type: 'text', label: '证件号码', grid: 6 / 24, placeholder: '请输入证件号码...', layout: { labelSpan: 7, wrapperSpan: 16 } },
            { name: 'BT', required: false, type: 'button-group', data: data, grid: 6 / 24 },
        ];

        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {/* <Button onClick={this.findSpqk.bind(this)}>{this.state.lable}</Button> */}
                        <EditFrom ref="findForm" daoName={daoName} controls={controlsFilter} selectFirst={false} clearItemMargin={true} />
                    </div>

                    <DataTable ref="MainTable" daoName={daoName} columns={columns} controls={controls} permID={permID} height={this.state.height} onSelectChange={this.onSelectChangeHandler.bind(this)} />
                </div>
                <div style={{ display: this.state.isDisplay_m }}>
                    <Row>
                        <Col span={24} >
                            <DataEditTable columns={columnsDivi} ref="table3" footer={false} multiSelect={true} keyName={"EMID"}
                                dataSource={this.state.diviDataSource}
                            />
                            <EditFrom ref="diviForm" daoName={daoName} controls={controlsDivi} />
                        </Col>
                    </Row>
                </div>
                <font style={{ display: this.state.isDisplay_o, fontSize: "20px", marginTop: 12 }}>
                    【认定申请审批情况】
                </font>
                <div style={{ display: this.state.isDisplay_o, marginTop: 12 }}>
                    <Row>
                        <Col span={24} >
                            <GrckrdspqkForm permID={permID} />
                        </Col>
                    </Row>
                </div>
            </div>
        )
    }
}
function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes, cmDate, offsetHeight, odsDate } = state.menus;
    return {
        userID,
        orgID,
        pOrgID,
        cmDate,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record,
        offsetHeight,
        odsDate
    }
}
XzgrckrdForm = connect(mapStateToProps)(XzgrckrdForm)
export default XzgrckrdForm;
let render = (props) => React.createElement(XzgrckrdForm, props);

let f = new Factory()
f.set("XzgrckrdForm", render)
